#include <iostream>
#include <vector>

#include "napi/native_api.h"
#include "napi_utils.h"

static napi_value RemoveFile(napi_env env, napi_callback_info info)
{
    utils::NapiCallbackInfo cbInfo(env, info);
    if (cbInfo.GetArgc() < 1 || !utils::IsString(env, cbInfo[0]))
    {
        utils::ThrowInvalidArg(env, "The first argument must be a string.");
        return nullptr;
    }
    std::string path = utils::GetValueStringUtf8(env, cbInfo[0]);
    if (path.empty())
    {
        utils::ThrowInvalidArg(env, "The first argument is an empty string.");
        return nullptr;
    }
    if (remove(path.c_str()) != 0)
    {
        napi_throw_error(env, "Remove file failed", path.c_str());
    }
    return nullptr;
}

static napi_value HelloWorld(napi_env, napi_callback_info)
{
    std::cout << "Hello World!" << std::endl;
    return nullptr;
}

static napi_value RunnerTest_Init(napi_env env, napi_value exports)
{
    std::vector<napi_property_descriptor> desc{
        {"removeFile", nullptr, RemoveFile, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"helloWorld", nullptr, HelloWorld, nullptr, nullptr, nullptr, napi_default, nullptr},
    };
    napi_define_properties(env, exports, desc.size(), desc.data());
    return exports;
}

static napi_module demoModule = {
    .nm_version = 1,
    .nm_flags = 0,
    .nm_filename = nullptr,
    .nm_register_func = RunnerTest_Init,
    .nm_modname = "runner_test",
    .nm_priv = ((void *)0),
    .reserved = {0},
};

extern "C" __attribute__((constructor)) void RegisterEntryModule(void)
{
    napi_module_register(&demoModule);
}
